package domain;


import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import data.JDBCUserDAO;


public class UserManager{
	
	private String userForm;
	private String passForm;
	
	private List<User> lu = new LinkedList<User>();
	
	public UserManager(){
		userForm="";
		passForm="";
	}
	
	public boolean logado(HttpServletRequest request){
		boolean logado = false;

        HttpSession session = request.getSession(false);

        userForm = request.getParameter("user");
        passForm = request.getParameter("password");

        if (session == null) {
                session = request.getSession();
                if (userForm == null || passForm == null
                                || userForm.length() == 0 || passForm.length() == 0) {
                        logado = false;

                } else {
                        if (valido(userForm, passForm)) {
                                logado = true;
                                session.setAttribute("session.user", userForm);
                        } else {
                                logado = false;
                        }

                }

        } else {
                if (userForm == null || passForm == null) {
                        logado = true;
                } else {
                        if (valido(userForm, passForm)) {
                                logado = true;
                                session.setAttribute("session.user", userForm);
                        } else {
                                logado = false;
                        }

                }
        }
        return logado;
}

	public boolean valido(String userForm, String passForm) {
        boolean res = false;
        
        lu = (new JDBCUserDAO()).selectAllUsers();
        for (Iterator iter = lu.iterator(); iter.hasNext();) {
            User u = (User) iter.next();
            if (u.getUser().equals(userForm) && u.getPass().equals(passForm)) {
                res = true;
            }
        }
        return res;
	}
}


